$(function () {

    $(window).resize(resize);
    function resize() {
        $('.btn-group').css({
            top: $('#contract').offset().top,
            right: ($(window).width() - 846) / 2 - 115
        });
        $('.btn-group').fadeIn(1500);
    }

    resize();
    var searchObj = parseSearch();
    $('.upload.before').attr('href', $('.upload.before').attr('href') + '?id=' + searchObj.id);
    $('.upload.single').attr('href', $('.upload.single').attr('href') + '?id=' + searchObj.id + '&type=single');
    $('.upload.couple').attr('href', $('.upload.couple').attr('href') + '?id=' + searchObj.id + '&type=double');
    searchObj.storeName = decodeURI(searchObj.storeName);

    var paper = {};

    $('.last-edit').click(function () {
        $('#contract').replaceWith(paper.body);
    });
    if (searchObj.storeName.indexOf('孚宝') > -1) {
        // if (true) {
        if (searchObj.type == 1) { // 孚宝转货权发货单
            var html = $.ajax({
                type: 'GET',
                url: 'http://' + getDomain() + '/admin/templets/bill/ZHANGJIAGANG_FUBAO_TRANSFER.html',
                async: false
            });
            getPaper_(html.responseText);
        } else {
            getPaper_();
        }
    } else if (searchObj.storeName.indexOf('孚宝') > -1) {
        var html = $.ajax({
            type: 'GET',
            url: 'http://' + getDomain() + '/admin/templets/bill/NINGXINGKU_' +
            (searchObj.type == 0 ? 'CARID' : (searchObj.type == 1 ? 'TRANSFER' : 'INTRO')) + '.html',
            async: false
        });
        getPaper_(html.responseText);
    } else if (searchObj.storeName.indexOf('宁兴') > -1) {
        var html = $.ajax({
            type: 'GET',
            url: 'http://' + getDomain() + '/admin/templets/bill/NINGXINGKU_' + (searchObj.type == 0 ? 'CARID' : (searchObj.type == 1 ? 'TRANSFER' : 'INTRO')) + '.html',
            async: false
        });
        getPaper_(html.responseText);
    } else if (searchObj.storeName.indexOf('太仓阳鸿石化有限公司') > -1) {
        var html = $.ajax({
            type: 'GET',
            url: 'http://' + getDomain() + '/admin/templets/bill/TAICANGYANGHONGKU_' + (searchObj.type == 0 ? 'CARID' : (searchObj.type == 1 ? 'TRANSFER' : 'INTRO')) + '.html',
            async: false
        });
        getPaper_(html.responseText);
    } else if (searchObj.storeName.indexOf('江苏省中油泰富石油集团有限公司') > -1) {
        var html = $.ajax({
            type: 'GET',
            url: 'http://' + getDomain() + '/admin/templets/bill/ZHANGJIAGANG_DAXIN_' + (searchObj.type == 0 ? 'CARID' :
                (searchObj.type == 1 ? 'TRANSFER' : 'INTRO')) + '.html',
            async: false
        });
        getPaper_(html.responseText);
        //
    } else if (searchObj.storeName.indexOf('江苏长江石油化工有限公司') > -1) {
        var html = $.ajax({
            type: 'GET',
            url: 'http://' + getDomain() + '/admin/templets/bill/CHANGJIANGSHIHUA_' + (searchObj.type == 0 ? 'INTRO_CARID' : (searchObj.type == 1 ? 'TRANSFER' : 'INTRO_CARID')) + '.html',
            async: false
        });
        getPaper_(html.responseText);
    } else if (searchObj.storeName.indexOf('张家港保税区长江国际港务有限公司') > -1) {
        if (searchObj.type == 1) {
            var html = $.ajax({
                type: 'GET',
                url: 'http://' + getDomain() + '/admin/templets/bill/ZHANGJIAGANG_CHANGJIANGGUOJI_TRANSFER.html',
                async: false
            });
            getPaper_(html.responseText);
        } else {
            getPaper_();
        }

    } else {
        getPaper_();
    }
    $('#signature').find('td').click(function (e) {
        if ($(this).closest('tr').index() == 0) {
            return;
        }
        if (!$('#signature').find('td').find('img').length || $('#signature').find('td').find('img').attr('src') == 'undefined') {
            return '';
        }
        $('#signature').find('td').removeClass('active');
        $(this).addClass("active");
        $('#contract').addClass('signature_')
    });

    function getPaper_(tmp_) {
        debugger;
        $.get('/ladingBill/getPaper/' + searchObj.id, function (data) {
            if (data.code == 200) {
                var obj = data.data;
                if (searchObj.action) {
                    if (data.data.signatureStatus && data.data.signatureStatus == 1) {
                        enableBtn($('.bill-change'));
                        var $authorized = $('.authorized');
                        $('.bill-change').click(function () {
                            $.when(getUserPermission("lading_bill:"))
                                .then(function (permission) {
                                        if ((paper.signatureStatus == 1 ) && permission['lading_bill:authorized_signature']) {
                                            enableBtn($authorized);
                                            onClick($authorized, function () {
                                                $.when(getUserSignature())
                                                    .then(function (com) {
                                                        if (com.tel == "1") {
                                                            return fnFail("超级管理员不能授权签章!")
                                                        }
                                                        if (com.signature || com.signaturePaper || com.signatureFinance) {
                                                            window.isChange = true;
                                                            signature(com, true);
                                                        } else {
                                                            alert("请上传公章!")
                                                        }
                                                    });
                                            })
                                        }
                                    }
                                )
                                .fail(function (e) {
                                    console.log(e);
                                });
                            var id = (Math.random() + "").split('.')[1];
                            $('#contract').click(function (event) {
                                if ($('.signature' + id).length) {
                                    $('.signature' + id).remove();
                                }
                                if ($(this).hasClass('paper-change')) { // 提单变更
                                    var $change = $('<div contenteditable="true" style="font-size: 22px;">变更内容</div> ');
                                    onClick($change, function (ev) {
                                        ev.stopPropagation();
                                        return false;
                                    });
                                    $(this).append($('<div></div>')
                                        .addClass('signature' + id)
                                        .css({
                                            position: 'absolute',
                                            width: '500px',
                                            height: '200px',
                                            border: '1px solid gray',
                                            left: event.pageX - $(this).offset().left - 100,
                                            top: event.pageY - $(this).offset().top - 100,
                                        })
                                        .append($change)
                                        .append('<span class="signature-ok" style="left: -1px;"><i class="fa fa-check"></i></span>')
                                        .append('<span class="signature-ok" style="left: 38px;"><i class="fa fa-times"></i></span>'))
                                }
                                $('.fa-times').closest('span').unbind('click').click(function (e) {
                                    if ($('.paper-change').length) {
                                        e.stopPropagation();
                                        $(this).closest('div').remove()
                                        $('.paper-change').removeClass("paper-change")
                                    }
                                });
                                onClick($('.fa-check').closest('span'), function (e) {
                                    if ($('.paper-change').length) {
                                        e.stopPropagation();
                                        if (confirm('确定变更?')) {
                                            $(this).closest('.signature' + id).css({
                                                border: 'none'
                                            }).end().siblings('span').remove().end().remove();
                                            $('.paper-change').removeClass("paper-change")
                                        }
                                    }

                                })
                            })
                        })
                    } else {
                        alert('提货单未授权签章，不能做变更');
                        window.close();
                    }
                }
                if (data.data.buyer) {
                    data.data.clienteleName = searchObj.clienteleName;
                    data.data.now = moment(Date.now()).format('YYYY年MM月DD日');
                    data.data.goodsName = data.data.goodsName || searchObj.goodsName;
                    data.data.tel = searchObj.tel || '';
                    data.data.no = data.data.no.replace('T', '');
                    data.data.depTel = decodeURIComponent(data.data.depTel);
                    data.data.depFax = decodeURIComponent(data.data.depFax);
                    var tmp = {};
                    console.log(data.data.list);
                    data.data.list.map(function (item) {
                        tmp[item.billBatch.split('-')[2]] = item;
                    });
                    console.log(tmp);
                    data.data.list = _.values(tmp);
                    $('#contract').html(ejs.render(tmp_ || (data.data.type == 0 ?
                            $('#template').html() : (data.data.type == 1 ? $('#template-transfer').html() : $('#template-intro').html())), data.data))
                } else {
                    $('#contract').replaceWith(data.data.paper_);
                }
                var paper = data.data;
                /***
                 *  授权签章
                 */
                var $authorized = $('.authorized'), $apply = $('.apply');
                disableBtn($authorized);
                disableBtn($apply);
                $.when(getUserPermission("lading_bill:"))
                    .then(function (permission) {
                            if ((paper.signatureStatus == 0 ) && permission['lading_bill:authorized_signature']) {
                                $apply.html('签章申请中');
                                enableBtn($authorized);
                                onClick($authorized, function () {
                                    $.when(getUserSignature())
                                        .then(function (com) {
                                            if (com.tel == "1") {
                                                return fnFail("超级管理员不能授权签章!")
                                            }
                                            if (com.signature || com.signaturePaper || com.signatureFinance) {
                                                signature(com);
                                            } else {
                                                alert("请上传公章!")
                                            }
                                        });
                                })
                            } else if (!paper.signatureStatus && permission['lading_bill:apply_signature']) {
                                enableBtn($apply);
                                onClick($apply, function () {
                                    $.post('/orderPaper/apply/' + searchObj.id + '/2', {visit: window.location.href}, function (res) {
                                        if (res.code == 200) {
                                            fnSuccess('申请成功!');
                                            disableBtn($apply);
                                            window.location = window.location;
                                        } else {
                                            alert(res.error || '操作失败!');
                                        }
                                    })
                                })
                            }
                        }
                    )
                    .fail(function (e) {
                        console.log(e);
                    });
                if (obj.status == 0) {
                    $('.after').hide();
                }
                if (obj.status == 1) {
                    $('.before').hide();
                    $('.after').css({'display': 'block'});
                    $('.preview-upload').css({'display': 'block'});
                }
                $('.to-pdf').click(function () {
                    $.post('/orderPaper/save-paper', {
                        orderId: searchObj.id,
                        orderType: "2", // 收货单类型
                        type: '0',
                        paper: getPaper()
                    }, function (xhr) {
                        if (xhr.code == 200) {
                            $('.to-pdf').attr('href', "/api/admin/ladingBill/back/" + searchObj.id + "-" + searchObj.clienteleName + ".pdf?id=" + searchObj.id);
                            window.location = "/api/admin/ladingBill/back/" + searchObj.id + "-" + searchObj.clienteleName + ".pdf?id=" + searchObj.id;
                        } else {
                            alert(xhr.error)
                        }
                    })
                });
                $('.edit').click(function () {
                    $(this).siblings('.edit-save').show();
                    $('#contract').addClass('editing');
                    $('.edit-lock').addClass("edit-locking");
                    $('.enableEdit').attr('contenteditable', true);
                    $(this).hide();
                });
                var saving = false;
                $('.edit-save').click(function () {
                    if (!saving) {
                        $(this).html('保存中...');
                        saving = true;
                    } else {
                        return alert('保存处理中...');
                    }
                    $('.edit-lock').removeClass("edit-locking");
                    $('.enableEdit').attr("contenteditable", false);
                    var self = this;
                    $.post('/ladingBill/save-paper', {
                        orderId: searchObj.id,
                        orderType: "2",
                        paper: getPaper()
                    }, function (xhr) {
                        saving = false;
                        if (xhr.code == 200) {
                            $(self).siblings('.edit').show();
                            $(self).hide();
                            $(self).html('保存').hide();
                            $('.enableEdit').attr('contenteditable', false);
                            $('#contract').removeClass('editing');
                            if (confirm("提单保存成功，是否关闭本页面?!")) {
                                window.close();
                            }
                        } else {
                            alert(xhr.error)
                        }
                    });
                });
                $('#contract').click(function (e) {
                    var $singature = $('.signature1');
                    if (window.isChange) {
                        $singature = $('.signature2');
                    }
                    if ($(this).hasClass('signature_')) {
                        if ($singature.length) {
                            $singature.remove();
                        }
                        if (!$('#signature .active img').length) {
                            return alert('请选择公章或签名!');
                        }
                        var $img = $('<img/> ').attr('src', $('#signature .active img').attr('src')).css({
                            width: '100%'
                        }).addClass('chapter');
                        $(this).append($('<div></div>')
                            .addClass('signature' + ($('.chapter').length + 1))
                            .css({
                                position: 'absolute',
                                width: '200px',
                                height: '200px',
                                border: '1px solid gray',
                                left: e.pageX - $(this).offset().left - 100,
                                top: e.pageY - $(this).offset().top - 100,
                            })
                            .append($img)
                            .append('<span class="signature-ok" style="left: -1px;"><i class="fa fa-check"></i></span>')
                            .append('<span class="signature-ok" style="left: 38px;"><i class="fa fa-times"></i></span>'))
                    }
                    $('.fa-times').unbind('click').click(function (e) {
                        e.stopPropagation();
                        $(this).closest('div').remove()
                    });
                    $('.fa-check').unbind('click').click(function (e) {
                        e.stopPropagation();
                        if (confirm('确定签章?')) {
                            $('.chapter').closest('.signature' + ($('.chapter').length)).css({
                                border: 'none'
                            }).end().siblings('span').remove().end().closest('span').remove();
                            $('#signature').hide();
                            $('#contract').removeClass('signature_');
                            savePaper("签章成功!");
                        }
                    })
                });
            } else {
                alert(data.error);
            }
        })
    }

    /**
     * 签章
     * isChange: 是否进行提单变更
     */
    function signature(com, isChange) {
        $('#signature').find('tr:nth-child(2) img').attr('src', com.signature);
        $('#signature').find('tr:nth-child(3) img').attr('src', com.signaturePaper);
        $('#signature').find('tr:nth-child(4) img').attr('src', com.signatureFinance);
        $('.enableEdit').attr('contenteditable', false);
        $('#signature').show();
    }

    function savePaper(msg) {
        $('.enableEdit').attr('contenteditable', false);
        debugger;
        $.post('/orderPaper/save-paper', {
            orderId: searchObj.id,
            orderType: "2", // 收货单类型
            type: '0',
            signatureStatus: '1',
            paper: getPaper()
        }, function (xhr) {
            if (xhr.code == 200) {
                alert(msg || '保存成功!');
                window.location = window.location;

            } else {
                alert(xhr.error)
            }
        })
    }

    $('.print').click(function () {
        $('.edit-lock').removeClass("edit-locking");
        $('#contract').removeClass('editing');
        if (getExplorer() == "IE") {
            pagesetup_null();
        }
        pagesetup_default();
        window.print();
    });

    function getPaper() {
        var str = $('#contract').prop('outerHTML');
        str = str.replace(/(<img[\s\S]*?>)/g, "$1</img>");
        return str;
    }

    function getExplorer() {
        var explorer = window.navigator.userAgent;
        //ie
        if (explorer.indexOf("MSIE") >= 0) {
            return "IE";
        }
        //firefox
        else if (explorer.indexOf("Firefox") >= 0) {
            return "Firefox";
        }
        //Chrome
        else if (explorer.indexOf("Chrome") >= 0) {
            return "Chrome";
        }
        //Opera
        else if (explorer.indexOf("Opera") >= 0) {
            return "Opera";
        }
        //Safari
        else if (explorer.indexOf("Safari") >= 0) {
            return "Safari";
        }
    }


    function pagesetup_default() {
        try {
            var RegWsh = new ActiveXObject("WScript.Shell")
            hkey_key = "header"
            RegWsh.RegWrite(hkey_root + hkey_path + hkey_key, "&w&b页码，&p/&P")
            hkey_key = "footer"
            RegWsh.RegWrite(hkey_root + hkey_path + hkey_key, "&u&b&d")

            //以下设置页面边距
            hkey_key = "margin_bottom";
            RegWsh.RegWrite(hkey_root + hkey_path + hkey_key, "0");
            hkey_key = "margin_left";
            RegWsh.RegWrite(hkey_root + hkey_path + hkey_key, "0.1");
            hkey_key = "margin_right";
            RegWsh.RegWrite(hkey_root + hkey_path + hkey_key, "0.1");
            hkey_key = "margin_top";
            RegWsh.RegWrite(hkey_root + hkey_path + hkey_key, "0.4");
        } catch (e) {
        }
    }

    var hkey_root, hkey_path, hkey_key
    hkey_root = "HKEY_CURRENT_USER";
    hkey_path = "\\Software\\Microsoft\\Internet Explorer\\PageSetup\\";
//设置网页打印的页眉页脚为空
    function pagesetup_null() {
        try {
            var RegWsh = new ActiveXObject("WScript.Shell");
            hkey_key = "header";
            RegWsh.RegWrite(hkey_root + hkey_path + hkey_key, "");
            hkey_key = "footer";
            RegWsh.RegWrite(hkey_root + hkey_path + hkey_key, "")
        } catch (e) {
        }
    }
})